package com.example.woke;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bean.BankAccountAndPayChannel;
import com.bean.BaseResponse;
import com.http.HttpMethods;
import com.jakewharton.rxbinding2.view.RxView;
import com.woke.data.Data_bindcarlist;
import com.woke.data.Datas_bankedcard;
import com.woke.data.UnionPayChannel;
import com.woke.diyview.Alertdialogall;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class TixianActivity extends Activity implements OnClickListener {

    private TextView mTzcaimoney;
    private Button mTok;
    private EditText mEmoney;
    private MyApp application;
    private float allmoney;
    private ArrayList<Data_bindcarlist> datalist = new ArrayList<Data_bindcarlist>();
    //	private DialogWidget mDialogWidget;//����֧������
    private LayoutInflater inflater;

    private RelativeLayout mRelite;
    private TextView mTcarno;
    private RelativeLayout mRelati1, mRelati2;
    private TextView mTbankedname;

    private String money;//��F���~
    private String cardno;//�y�п�
    private String name;//����
    private String phone;//�֙C
    private String carbank;//�y������
    private String sfzno;//����C̖
    private String bindid = "";//�󶨺�

    private Tixianreciver reciver;
    private float timoney;
    private String getuser_money;
    private Alertdialogall zidingy;
    private String payWay;

    AlertDialog bindardAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tixian);

        Intent intent = getIntent();
        payWay = intent.getStringExtra("payWay");
        application = (MyApp) getApplication();
        zidingy = new Alertdialogall();
        if (application.getDatas_load() != null) {
            getuser_money = application.getDatas_load().getUser_money();
        }
        Log.e("getuser_money", getuser_money);
        if (getuser_money.equals("") || null == getuser_money) {
        } else {
            allmoney = Float.parseFloat(getuser_money);
        }
        intview();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (reciver != null) {
            unregisterReceiver(reciver);
        }
    }

    class Tixianreciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extras = intent.getExtras();
            Log.e("extras", "extras");

            ArrayList<String> list = extras.getStringArrayList("tixian1");
            mTbankedname.setText(list.get(4));
            cardno = list.get(2);
            name = list.get(0);
            phone = list.get(3);
            sfzno = list.get(1);
            bindid = list.get(5);
//			mTcarno.setText ("尾号" + list.get (2)
//					.substring (list.get (2).length () - 4, list.get (2).length ()));
            String f_tail_number = getResources().getString(R.string.f_tail_number);
            mTcarno.setText(String.format(f_tail_number, list.get(2)
                    .substring(list.get(2).length() - 4, list.get(2).length())));
        }
    }

    private void intview() {
        inflater = getLayoutInflater();

        reciver = new Tixianreciver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.woke.tixian");
        TixianActivity.this.registerReceiver(reciver, filter);

        findViewById(R.id.avtixian_image_back).setOnClickListener(this);
        mTok = (Button) findViewById(R.id.avtixian_text_tixian);
        RxView.clicks(mTok)
                .throttleFirst(2, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        //防抖动,避免多次操作
                        goToRecharge();
                    }
                });
//		mTok.setOnClickListener (this);
        mTzcaimoney = (TextView) findViewById(R.id.avtixian_text_zcaimoney);
        mEmoney = (EditText) findViewById(R.id.avtixian_edit_money);//���ֽ��
        mTcarno = (TextView) findViewById(R.id.avtixian_text_cardno);
        mRelite = (RelativeLayout) findViewById(R.id.avtixian_relatie_morebank);//�а�
        mTbankedname = (TextView) findViewById(R.id.avtixian_text_bankname);
        mRelite.setOnClickListener(this);
        mRelati1 = (RelativeLayout) findViewById(R.id.avtixian_frame1);
        mRelati2 = (RelativeLayout) findViewById(R.id.avtixian_frame2);
        mTzcaimoney.setText("余额 " + getuser_money);
        mEmoney.addTextChangedListener(watcher1);

        getbanklistAndUnionPayChannel();

    }


    private ArrayList<Datas_bankedcard> mBankedCards = new ArrayList<Datas_bankedcard>();
    private ArrayList<UnionPayChannel> mUnionPayChannels = new ArrayList<>();
    private static final int REQUEST_BIND_CARD = 8;  //绑卡请求动作
    private static final int REQUEST_AUTH_PAY_PASSWORD = 10; //支付密码验证

    /**
     * 获取银行卡列表和渠道
     */
    private void getbanklistAndUnionPayChannel() {
        if (application.getDatas_load() != null) {

            int userid = Integer.parseInt(application.getDatas_load().getId());
            HttpMethods.getInstance()
                    .getBankAccountAndUnionPayChannel(mAccountsAndChannelsObserver, userid, 1, 3);
        }
    }

    private Observer<BankAccountAndPayChannel> mAccountsAndChannelsObserver = new Observer<BankAccountAndPayChannel>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BankAccountAndPayChannel value) {
            if (value != null) {
                List<Datas_bankedcard> baList = value.getBanklist();
//				List<UnionPayChannel> clist = value.getGalllist ();
                if (baList != null && baList.size() > 0) {
                    mBankedCards.clear();
                    mBankedCards.addAll(baList);
                }
                if (mBankedCards.size() > 0) {
                    for (int i = 0; i < mBankedCards.size(); i++) {
                        Datas_bankedcard data = mBankedCards.get(i);
                        if (data.type.equals("1")){
                            mRelite.setVisibility(View.VISIBLE);
                            Log.e("Datas_bankedcard",data.toString());
                            mTbankedname.setText(data.brname);
                            mTcarno.setText("尾号" + data.cardno.substring(data.cardno.length() - 4, data.cardno
                                    .length()));
                            cardno = data.cardno;
                            name = data.name;
                            phone = data.phone;
                            carbank = data.brname;
                            break;
                        }
                    }
                } else {
//                    Toast.makeText(TixianActivity.this, "请先绑定一张银行号后在支付", Toast.LENGTH_SHORT)
//                            .show();
//                    Intent intent = new Intent(TixianActivity.this, MywalletcardActivity.class);
//                    intent.putExtra("czhiortxian", "no");
//                    startActivityForResult(intent, REQUEST_BIND_CARD);
                    aralogid("还未绑卡","前去绑卡");
                    return;
                }
//
//				if (clist != null && clist.size () > 0) {
//					mUnionPayChannels.clear ();
//					mUnionPayChannels.addAll (clist);
//					if (mChannelAdapter != null) {
//						mChannelAdapter.notifyDataSetChanged ();
//					}
//				}


            }
        }

        @Override
        public void onError(Throwable e) {

            Toast.makeText(TixianActivity.this, e.getMessage(), Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onComplete() {

        }
    };

    private TextWatcher watcher1 = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String trim = "" + mEmoney.getText().toString().trim();
            if (trim.equals("")) {
                mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightgray));
            } else {
                mTok.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_lightred));
            }

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 95 && resultCode == 96) {
            ArrayList<String> datlist = data.getStringArrayListExtra("tixian1");
            mTbankedname.setText(datlist.get(4));
            cardno = datlist.get(3);
            name = datlist.get(0);
            phone = datlist.get(2);
            sfzno = datlist.get(1);
            carbank = datlist.get(4);
            mTcarno.setText("尾号" + datlist.get(3)
                    .substring(datlist.get(3).length() - 4, datlist.get(3).length()));
        } else if (requestCode == REQUEST_AUTH_PAY_PASSWORD && resultCode == 600) {

            cashAdvance(timoney, name, cardno, 74);//

//			tixiandata ("" + timoney, cardno, name, phone, carbank);


        } else if (requestCode == REQUEST_BIND_CARD) {
            //请求绑卡 的请求码
            getbanklistAndUnionPayChannel();
        }

    }

    /**
     * 提现  way 默认传1
     */
    private void cashAdvance(float amount, String name, String card_no, int way) {
        Datas_load datasLoad = application.getDatas_load();
        if (application.getDatas_load() != null) {
            mRelati2.setVisibility(View.VISIBLE);
            HttpMethods.getInstance()
                    .cashAdvance(mCashObserver, Integer.parseInt(datasLoad.getId()), amount, name, card_no, 74);

        }
    }

    private Observer<BaseResponse> mCashObserver = new Observer<BaseResponse>() {
        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(BaseResponse value) {
            if (value != null && value.resultSuccess()) {
                Toast.makeText(TixianActivity.this, "提现成功", Toast.LENGTH_SHORT).show();
                Log.e("提现", value.toString());
                mTok.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            } else {
                String info="提现失败,请稍后重试";
                if (value != null) {
                    Log.e("提现", value.toString());
                             info=value.getInfo();
                            if (value.getData()!=null);
                }

                Toast.makeText(TixianActivity.this, info, Toast.LENGTH_SHORT).show();
            }
            mRelati2.setVisibility(View.GONE);
        }

        @Override
        public void onError(Throwable e) {
            Toast.makeText(TixianActivity.this, "系统服务繁忙,请稍后重试", Toast.LENGTH_SHORT).show();
            mRelati2.setVisibility(View.GONE);
        }

        @Override
        public void onComplete() {
            mRelati2.setVisibility(View.GONE);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.avtixian_image_back:
                finish();
                break;

            case R.id.avtixian_relatie_morebank:
                Intent intent = new Intent(TixianActivity.this, MybankblindActivity.class);
                intent.putExtra("czhiortxian", "tixian");//�н����r���D
                startActivityForResult(intent, 95);
                break;

//			case R.id.avtixian_text_tixian:
////				Checkpaypsw check = new Checkpaypsw ();
//				goToRecharge ();
//				break;

            default:
                break;
        }
    }

    private void goToRecharge() {
        if (application.getDatas_load() == null) return;
        if (null == application.getDatas_load()
                .getPay_pwd() || application.getDatas_load().getPay_pwd().equals("")) {
            zidingy.aralogid(TixianActivity.this, "还未设置支付密码", "前往设置？");
        } else {
            money = "" + mEmoney.getText().toString().trim();
            if (money.equals("")) {
                Toast.makeText(TixianActivity.this, "请输入金额", Toast.LENGTH_SHORT).show();
            } else {
                float parseInt = Float.parseFloat(money);

                boolean textline = false;//�ж�С���λ���Ƿ񳬹�
                int indexOf = money.indexOf('.');
                int length = money.length();
                if (indexOf > -1) {
                    if ((length - indexOf - 1) > 2) {
                        textline = true;
                    }
                }

//					int parseInt = Integer.parseInt(money);
                if (parseInt < 1) {
                    Toast.makeText(TixianActivity.this, "提现最小金额需大于1元", Toast.LENGTH_SHORT)
                            .show();
                } else if (textline == true) {
                    Toast.makeText(TixianActivity.this, "金额小数点后最多2位", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    timoney = parseInt;
                    Intent intent1 = new Intent(TixianActivity.this, CheckpaypswActivity.class);
                    intent1.putExtra("paymoney", money);
                    startActivityForResult(intent1, REQUEST_AUTH_PAY_PASSWORD);
                }
            }
        }
    }
    private void aralogid(String info, String kll) {
        bindardAd = new AlertDialog.Builder(TixianActivity.this).
                setTitle(info).
                setMessage(kll).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(TixianActivity.this, MywalletcardActivity.class);
                    intent.putExtra("czhiortxian", "no");
                    startActivityForResult(intent, REQUEST_BIND_CARD);
                        bindardAd.dismiss();
                    }
                }).
                setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        bindardAd.dismiss();
                    }
                }).create();
        bindardAd.show();
    }
}
